"""
管理火车上线或者下线
"""
import json
import time
import _thread
try:
    from shared_types import UpHeartbeatMsg, ConnectedMsg
except ImportError:
    pass
from .communications import onboard_sender
from .states import states
# from bootstrap
from bootstrap.udp_broadcast import broadcast_udp_msg
from bootstrap.configs import configs, UDP_DISCOVERY_PORT


class KeepAlive:
    def __init__(self) -> None:
        self._keepalive_thread = None

    def keep_alive(self):
        msg: "UpHeartbeatMsg" = {
            "name": configs.config["name"], "type": "ETT_HEARTBEAT_UP"}
        keepalive_msg = json.dumps(msg).encode('ascii')
        while True:
            if states.connection_status == 'connected' and states.control_station_ip != "":
                if time.time() - states.last_keepalive_time < 12:  # 距离上次保活10s以下
                    onboard_sender.send(
                        states.control_station_ip, keepalive_msg)
                else:
                    states.connection_status = 'disconnected'
            elif states.connection_status == 'disconnected':
                data: "ConnectedMsg" = {"type": "ETT_JOIN",
                                        "ip": states.bootstrap_states.ip,
                                        "mask": states.bootstrap_states.mask,
                                        "name": configs.config['name'],
                                        'role': configs.config['role']}
                if states.bootstrap_states.network_initialized():
                    broadcast_udp_msg(states.bootstrap_states.ip, UDP_DISCOVERY_PORT,
                                      states.bootstrap_states.mask,  json.dumps(data).encode('ascii'))
                    print("sent connectedMsg to control station")
                    time.sleep(2)
            print(states.connection_status, states.last_keepalive_time)
            time.sleep(3)

    def start(self):
        """
        Start listening to socket
        """
        self._th = _thread.start_new_thread(self.keep_alive, ())
